#include "bsp_key.h"
#include "bsp_flash.h"
#include "bsp_can.h"
#include "app_key.h"

/*
增益数据和车载显示盘上显示增益对应关系
增益为偶数：[00 -> 02 –> 04 -> … -> 28]
*/
stc_gain_t gain =
{
		20,		/*value*/
        0,	
};  /*刹车增益*/


/*
2个独立的IO口按键
PA4 -- Key1
PB1 -- Key2
*/
void BSP_Key_Init(void)
{
	stc_gpio_cfg_t stcGpioCfg;  
    ///< 打开GPIO外设时钟门控
    Sysctrl_SetPeripheralGate(SysctrlPeripheralGpio, TRUE); 
    ///< 端口方向配置->输入
    stcGpioCfg.enDir = GpioDirIn;
    ///< 端口上下拉配置-> none
    stcGpioCfg.enPu = GpioPuEnable; /*外部有上拉电阻*/
    stcGpioCfg.enPd = GpioPdDisable;
	//stcGpioCfg.enDrv = GpioDrvH;
	stcGpioCfg.enCtrlMode = GpioAHB;	
    Gpio_Init(GpioPortB, GpioPin1, &stcGpioCfg);
	Gpio_Init(GpioPortA, GpioPin4, &stcGpioCfg);	
}


static uint8_t  key_index_find(uint8_t i)
{
	switch(i)
	{
		case 0:
		return KEY1_PRESSED;
		case 1:
		return (KEY2_PRESSED<<1);
//	    case 2:
//		return KEY3_PRESSED; 
//		case 3:
//		return KEY4_PRESSED;
//		case 4:
//		return KEY5_PRESSED;		
		default:
			break;
	}
  return 0;
}

/**********************************************************
* 函数名： Key_read(void) 
* 说明：读取按键值.
*	输入参数:void
* 输出参数: 按键1为1，按键2为2，没有按下为0
*********************************************************/
uint8_t key_read()
{
	uint8_t ret= 0;
  for(uint8_t i = 0;i < KEY_TOTALS; i++)
	{
			ret |= key_index_find(i);
	}
	return ret;
}


void key_gain_update(uint8_t key)
{
		static uint8_t last_gain;

		if (key == 1)
		{
				if(gain.value < 0x28)
				{
					gain.value += 2;
				}
        gain.active_flg = TRUE;           
		}
		else if (key == 2)
		{
				if(gain.value)
				{
					gain.value -= 2;
				}
        gain.active_flg = TRUE;  
		}	
		
		if(last_gain != gain.value)
		{		
			Flash_WriteConfig(gain.value);	
			return;
		}
		last_gain = gain.value;
}

/******************************************
0x0a : key1 pressed 
0x01 : key1 release

0x0b : key2 pressed 
0x02 : key2 release

*********************************************/
uint8_t Key_scan(void)
{	
		static uint8_t active_flag;
		uint8_t key = key_read();
		if (key > 0) //有按键按下
		{
				if (APP_CAN.key_cnt > 1000) //非5秒内按下,先激活
				{
						active_flag = 1;
						return 0;
				}
				else
				{
						if (APP_CAN.key_press_cnt > 200) //长按1秒后，每200ms更新键值
						{
								if (((APP_CAN.key_press_cnt -200) % 40) == 0) //达到200ms更新
								{
										key_gain_update(key);
								}
						}
						else if (APP_CAN.key_press_cnt == 5)  //短按25ms后
						{
								key_gain_update(key);
						}
				}
				APP_CAN.key_cnt = 0;
		}
		else
		{
				APP_CAN.key_press_cnt = 0;
				if (active_flag)  //等待弹起后，激活按键，避免上一次按键清计数后执行
				{
						APP_CAN.key_cnt = 0;
						active_flag = 0;
				}
		}

    return key;
}




